/*
 * Copyright 2016. SHENQINCI(沈钦赐)<946736079@qq.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package uutalk.netcloud.talk.base.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.util.view.ToastUtil;

/**
 * 数量、增加和减少控制按钮。
 */
public class NumberButton extends LinearLayout implements View.OnClickListener{
    //最大数，默认无限制
    private int mMaxNum = Integer.MAX_VALUE;
    private TextView mCount;
    private OnDataListener mOnDataListener;
    private View numberInputView;
    AlertDialog alertDialog = null;

    public NumberButton(Context context) {
        this(context, null);
    }

    public NumberButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout, this);
        TextView addButton = (TextView) view.findViewById(R.id.button_add);
        addButton.setOnClickListener(this);
        TextView subButton = (TextView) findViewById(R.id.button_sub);
        subButton.setOnClickListener(this);

        //编辑数字
        mCount = ((TextView) findViewById(R.id.text_count));
        mCount.setOnClickListener(this);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberButton);
        boolean editable = typedArray.getBoolean(R.styleable.NumberButton_editable, true);
        int buttonWidth = typedArray.getDimensionPixelSize(R.styleable.NumberButton_buttonWidth, -1);
        int textWidth = typedArray.getDimensionPixelSize(R.styleable.NumberButton_textWidth, -1);
        int textSize = typedArray.getDimensionPixelSize(R.styleable.NumberButton_nbtextSize, -1);
        int textColor = typedArray.getColor(R.styleable.NumberButton_nbtextColor, 0xff000000);
        typedArray.recycle();
        mCount.setTextColor(textColor);
        subButton.setTextColor(textColor);
        addButton.setTextColor(textColor);

        if (textSize > 0)
            mCount.setTextSize(textSize);

        if (buttonWidth > 0) {
            LayoutParams textParams = new LayoutParams(buttonWidth, LayoutParams.MATCH_PARENT);
            subButton.setLayoutParams(textParams);
            addButton.setLayoutParams(textParams);
        }
        if (textWidth > 0) {
            LayoutParams textParams = new LayoutParams(textWidth, LayoutParams.MATCH_PARENT);
            mCount.setLayoutParams(textParams);
        }
    }

    public int getNumber() {
        try {
            return Integer.parseInt(mCount.getText().toString());
        } catch (NumberFormatException e) {
        }
        mCount.setText("1");
        return 1;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        int count = getNumber();
        if (id == R.id.button_sub) {
            if (count > 1) {
                //正常减
                mCount.setText("" + (count - 1));
                onCurNumberChange(count - 1);
            }

        } else if (id == R.id.button_add) {
            if (count < mMaxNum) {
                //正常添加
                mCount.setText("" + (count + 1));
                onCurNumberChange(count + 1);
            } else {
                //正常添加
                mCount.setText("" + 1);
                onCurNumberChange(1);
            }
        } else if (id == R.id.text_count) {
            //setEditable(true);
            //mCount.setSelection(mCount.getText().toString().length());
            AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
            alertDialog = builder.setView(getNumberInputView()).create();
            alertDialog.show();

        }
    }

    private View getNumberInputView(){

        //if(numberInputView == null)
        {
            numberInputView = LayoutInflater.from(this.getContext()).inflate(R.layout.layout_number_input, null);
        }
        EditText editText = numberInputView.findViewById(R.id.et_num_input);
        Button cancel = numberInputView.findViewById(R.id.btn_cancel);
        Button btn_comfirm = numberInputView.findViewById(R.id.btn_comfirm);
        editText.setText(""+getNumber());
        editText.setSelection(editText.getText().toString().length());
        cancel.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        btn_comfirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                String strNum = editText.getText().toString();
                if(TextUtils.isEmpty(strNum)){
                    ToastUtil.makeToast(getResources().getText(R.string.str_err_channel));
                } else {
                    int iNum = Integer.parseInt(strNum);
                    if (iNum <= 0) {
                        //手动输入
                        editText.setText("1");
                        editText.setSelection(editText.getText().toString().length());
                        ToastUtil.makeToast(getResources().getText(R.string.str_err_channel_small));
                    } else if (iNum > mMaxNum) {
                        //超过了数量
                        editText.setText(mMaxNum + "");
                        editText.setSelection(editText.getText().toString().length());
                        ToastUtil.makeToast(getResources().getText(R.string.str_err_channel_big));
                    } else {
                        mCount.setText(iNum+"");
                        onCurNumberChange(iNum);
                        alertDialog.dismiss();
                    }
                }
            }
        });
        return numberInputView;
    }


    private void onCurNumberChange(int num){
        if (mOnDataListener != null) mOnDataListener.onCurNumberChange(num);
    }

    public NumberButton setCurrentNumber(int currentNumber) {
        if (currentNumber < 1) mCount.setText("1");
        mCount.setText(""+Math.min(mMaxNum, currentNumber));
        return this;
    }


    public int getMaxNum() {
        return mMaxNum;
    }

    public NumberButton setMaxNum(int maxNum) {
        if(maxNum < 1){
            mMaxNum = Integer.MAX_VALUE;
        } else {
            mMaxNum = maxNum;
        }
        return this;
    }

    public NumberButton setOnDataListener(OnDataListener onDataListener) {
        mOnDataListener = onDataListener;
        return this;
    }

    public interface OnDataListener {
        void onCurNumberChange(int num);
    }
}
